import { fileURLToPath } from 'node:url'
import { dirname } from 'node:path'
import plugin from '../../../lib/plugins/plugin.js'
import api from '../core/api.js'
import favorLevel from '../core/favorLevel.js'
import fs from 'node:fs/promises'
import path from 'node:path'
import os from 'node:os'
import { segment } from 'oicq'
import rendererLoader from '../../../lib/renderer/loader.js'





const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 签到配置
const signInConfig = {
  // 签到基础金币奖励
  baseGoldReward: 50,
  // 连续签到额外金币奖励（每天增加）
  consecutiveGoldBonus: 5,
  // 签到基础好感度经验奖励
  baseFavorExperience: 20,
  // 连续签到额外好感度经验奖励（每天增加）
  consecutiveFavorBonus: 2,
  // 道具掉落概率
  itemDropRate: 0.2
}

// 导入道具功能
import items, { registerItem } from './items.js'

import menuManager from '../../systemDB/menu/menu.js'





export class SignIn extends plugin {
  constructor() {
    super({
      name: '签到系统',
      dsc: '每日签到获得金币和好感度',
      event: 'message',
      priority: 500,
      rule: [
        {
          reg: '^(?:#|/)?签到$',
          fnc: 'signIn'
        }
      ]
    })

    // 延迟注册道具，确保数据库已初始化
    setTimeout(async () => {
      try {
        await registerItem();
      } catch (err) {
        console.error('在SignIn插件初始化时注册道具失败:', err);
      }
    }, 3000);
  }

  // 初始化插件
  async init() {
    // 注册到菜单
    await this.registerToMenu()
  }

  // 注册到系统菜单
  async registerToMenu() {
    const pluginInfo = {
      name: '签到系统',
      dsc: '每日签到获得金币和好感度',
      cmds: ['#签到']
    }
    await menuManager.registerPluginMenu(pluginInfo)
  }

 

  async signIn() {
    const userId = this.e.user_id
    const isGroup = this.e.isGroup
    const groupId = isGroup ? this.e.group_id : null

    // 获取签到信息检查是否已签到
    const signInInfo = await api.getUserSignInInfo(userId)
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

    let isDuplicate = false
    if (signInInfo.lastSignIn) {
      const lastSignInDate = new Date(signInInfo.lastSignIn.getFullYear(), signInInfo.lastSignIn.getMonth(), signInInfo.lastSignIn.getDate())
      if (lastSignInDate.getTime() === today.getTime()) {
        isDuplicate = true
      }
    }

    // 只有非重复签到才计算奖励和更新信息
    let reward = { gold: 0, favorExperience: 0 }
    let updateResult = signInInfo
    let usedDoubleCard = false
    let droppedItem = false
    if (!isDuplicate) {
      // 计算签到奖励
      const consecutiveDays = signInInfo.consecutiveDays || 0
      reward = {
        gold: signInConfig.baseGoldReward + (consecutiveDays * signInConfig.consecutiveGoldBonus),
        favorExperience: signInConfig.baseFavorExperience + (consecutiveDays * signInConfig.consecutiveFavorBonus)
      }

      // 检查并使用好感度双倍卡
      usedDoubleCard = await items.checkAndUseDoubleFavorCard(userId)
      if (usedDoubleCard) {
        reward.favorExperience *= 2
      }

      // 更新签到信息和增加金币
      updateResult = await api.updateSignInInfo(userId, reward.gold)

      // 添加好感度经验
      await favorLevel.addUserExperience(userId, reward.favorExperience)

      // 更新总签到天数
      await api.updateUserTotalSignInDays(userId)

      // 签到掉落道具
      droppedItem = await items.dropItemOnSignIn(userId)
    }



    // 获取用户信息
    const userInfo = {
      gold: await api.getUserGold(userId),
      signInInfo: updateResult,
      uid: await api.getUserUID(userId),
      favorInfo: await favorLevel.getUserFavorLevelInfo(userId),
      totalSignInDays: await api.getUserTotalSignInDays(userId),
      isDuplicate: isDuplicate,
      usedDoubleCard: usedDoubleCard,
      droppedItem: droppedItem
    }

    // 生成签到图片
    const imagePath = await this.generateSignInImage(userId, userInfo, reward)

    // 发送图片
    await this.reply([segment.image(imagePath)])

    // 清理临时图片
    setTimeout(() => {
      fs.unlink(imagePath).catch(err => {
        console.error('删除临时图片失败:', err)
      })
    }, 60000)

    return true
  }

  // 生成签到图片
  async generateSignInImage(userId, userInfo, reward) {
    // 读取HTML模板
    const templatePath = path.join(__dirname, 'template.html')
    let template
    try {
      template = await fs.readFile(templatePath, 'utf8')
    } catch (err) {
      console.error('读取模板失败:', err)
      // 如果模板不存在，使用默认模板
      template = this.getDefaultTemplate()
    }

    // 检查是否存在背景图片
    let backgroundImage = ''
    const resourcesDir = path.join(__dirname, 'resources')
    const pngPath = path.join(resourcesDir, '001.png')
    const jpgPath = path.join(resourcesDir, '001.jpg')
    
    try {
      // 优先使用png格式
      if (await fs.access(pngPath).then(() => true).catch(() => false)) {
        backgroundImage = pngPath
      } else if (await fs.access(jpgPath).then(() => true).catch(() => false)) {
        backgroundImage = jpgPath
      }
    } catch (err) {
      console.error('检查背景图片失败:', err)
    }

    // 计算进度百分比
    const progressPercentage = Math.min(100, Math.floor((userInfo.favorInfo.experience / userInfo.favorInfo.nextLevelExperience) * 100))

    // 替换模板变量
    template = template
      .replace('{{uid}}', userInfo.uid)
      .replace('{{gold}}', userInfo.gold)
      .replace('{{totalSignInDays}}', userInfo.totalSignInDays)
      .replace('{{consecutiveDays}}', userInfo.signInInfo.consecutiveDays)
      .replace('{{rewardGold}}', reward.gold)
      .replace('{{rewardFavor}}', reward.favorExperience)
      .replace('{{favorLevel}}', userInfo.favorInfo.level)
      .replace('{{favorExperience}}', userInfo.favorInfo.experience)
      .replace('{{nextLevelExperience}}', userInfo.favorInfo.nextLevelExperience)
      .replace('{{progressPercentage}}', progressPercentage)
      
    // 如果存在背景图片，添加到模板中
    if (backgroundImage) {
      // 确保路径使用正斜杠
      const formattedPath = backgroundImage.replace(/\\/g, '/')
      template = template.replace(
        '<style>',
        `<style>
          body {
            background-image: url('file:///${formattedPath}');
            background-size: cover;
            background-position: center;
          }`
      )
    }

    // 处理道具使用和掉落信息
    let extraMessages = ''
    if (userInfo.usedDoubleCard) {
      extraMessages += '\n      <div class="reward" style="border-left: 4px solid #4096ff;">\n        <div class="reward-title">道具使用</div>\n        <div class="info-item">\n          <span class="value highlight">使用了好感度值双倍卡，获得双倍好感度！</span>\n        </div>\n      </div>'
    }
    if (userInfo.droppedItem && !userInfo.isDuplicate) {
      extraMessages += '\n      <div class="reward" style="border-left: 4px solid #67c23a;">\n        <div class="reward-title">道具掉落</div>\n        <div class="info-item">\n          <span class="value highlight">恭喜获得好感度值双倍卡！</span>\n        </div>\n      </div>'
    }

    // 处理重复签到情况
    if (userInfo.isDuplicate) {
      template = template
        .replace('签到成功', '今日已签到')
        .replace('✅', '⏰')
        .replace('<div class="reward">', '<div class="reward" style="display: none;">')
        .replace('</div>\n    </div>\n  </div>\n</body>\n</html>', '\n      <div class="reward" style="border-left: 4px solid #ff4d4f;">\n        <div class="reward-title">提示</div>\n        <div class="info-item">\n          <span class="value highlight">你今天已经签到过了，明天再来吧～</span>\n        </div>\n      </div>' + extraMessages + '\n    </div>\n  </div>\n</body>\n</html>')
    } else if (extraMessages) {
      template = template.replace('</div>\n    </div>\n  </div>\n</body>\n</html>', extraMessages + '\n    </div>\n  </div>\n</body>\n</html>')
    }

    // 生成临时HTML文件
    // 创建项目内临时目录
const tempDir = path.join(process.cwd(), 'temp', 'signIn');
await fs.mkdir(tempDir, { recursive: true });
const tempHtmlPath = path.join(tempDir, `sign_in_${userId}_${Date.now()}.html`)
    await fs.writeFile(tempHtmlPath, template)

    // 使用渲染器生成图片
      const renderer = rendererLoader.getRenderer()
    const imagePath = path.join(tempDir, `sign_in_${userId}_${Date.now()}.png`)

    try {
        // 为Windows系统格式化文件路径
        const fileUrl = tempHtmlPath.replace(/\\/g, '/').replace(':', ':/');
        await renderer.render('signIn', {
          tplFile: tempHtmlPath,
          saveId: `sign_in_${userId}_${Date.now()}`,
          path: imagePath,
          width: 800,
          height: 600
        })
      } catch (err) {
        console.error('生成图片失败:', err)
        throw new Error('生成签到图片失败')
      } finally {
        // 清理临时HTML文件
        await fs.unlink(tempHtmlPath).catch(err => {
          console.error('删除临时HTML文件失败:', err)
        })
      }

    return imagePath
  }

  // 默认HTML模板
  getDefaultTemplate() {
    return `
      <!DOCTYPE html>
      <html lang="zh-CN">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>签到结果</title>
        <style>
          body { font-family: 'Microsoft YaHei', sans-serif; background-color: #f5f5f5; margin: 0; padding: 20px; }
          .container { max-width: 600px; margin: 0 auto; background-color: white; border-radius: 10px; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
          .title { text-align: center; color: #333; font-size: 24px; margin-bottom: 20px; }
          .info { margin: 20px 0; }
          .info-item { margin: 15px 0; display: flex; justify-content: space-between; padding-bottom: 10px; border-bottom: 1px dashed #eee; }
          .label { font-weight: bold; color: #666; font-size: 16px; }
          .value { color: #333; font-size: 16px; }
          .reward { background-color: #f9f9f9; padding: 15px; border-radius: 5px; margin: 20px 0; }
          .reward-title { color: #e6a23c; font-weight: bold; margin-bottom: 10px; font-size: 18px; }
          .favor-bar { height: 10px; background-color: #eee; border-radius: 5px; margin-top: 5px; overflow: hidden; }
          .favor-progress { height: 100%; background-color: #4096ff; }
          .highlight { color: #e6a23c; font-weight: bold; }
        </style>
      </head>
      <body>
        <div class="container">
          <h1 class="title">签到成功</h1>
          <div class="info">
            <div class="info-item">
              <span class="label">用户ID:</span>
              <span class="value">{{uid}}</span>
            </div>
            <div class="info-item">
              <span class="label">当前金币:</span>
              <span class="value highlight">{{gold}}</span>
            </div>
            <div class="info-item">
              <span class="label">总签到天数:</span>
              <span class="value">{{totalSignInDays}}</span>
            </div>
            <div class="info-item">
              <span class="label">连续签到:</span>
              <span class="value">{{consecutiveDays}}天</span>
            </div>
            <div class="info-item">
              <span class="label">好感度等级:</span>
              <span class="value">{{favorLevel}}</span>
            </div>
            <div class="info-item">
              <span class="label">当前经验:</span>
              <span class="value">{{favorExperience}}/{{nextLevelExperience}}</span>
            </div>
            <div class="favor-bar">
              <div class="favor-progress" style="width: {{progressPercentage}}%"></div>
            </div>
          </div>
          <div class="reward">
            <div class="reward-title">签到奖励</div>
            <div class="info-item">
              <span class="label">金币奖励:</span>
              <span class="value highlight">{{rewardGold}}</span>
            </div>
            <div class="info-item">
              <span class="label">好感度经验:</span>
              <span class="value highlight">{{rewardFavor}}</span>
            </div>
          </div>
        </div>
      </body>
      </html>
    `
  }
}